package handle

import (
	"bufio"
	"bytes"
	"fmt"
	"log"
	"net/http"
	"os"
	"strings"

	"github.com/pelletier/go-toml/v2"
)

type Tx string

const (
	unknown   Tx = "unknown"
	versions  Tx = "versions"
	libraries Tx = "libraries"
	plugins   Tx = "plugins"
	bundles   Tx = "bundles"
)

func DecodeToml(path string) LibVersion {
	open, err := os.ReadFile(path)
	if err != nil {
		panic(err)
	}
	scanner := bufio.NewScanner(bytes.NewReader(open))
	scanner.Split(bufio.ScanLines)

	var data LibVersion
	buffer := bytes.NewBuffer(nil)
	pre := unknown
	cur := unknown
	var parse bool
	for scanner.Scan() {
		line := scanner.Text()
		trim := strings.TrimSpace(line)
		if len(trim) == 0 {
			continue
		}
		switch trim {
		case "[versions]":
			cur = versions
		case "[libraries]":
			pre = cur
			cur = libraries
			parse = true
			break

		case "[plugins]":
			pre = cur
			cur = plugins
			parse = true
			break

		case "[bundles]":
			pre = cur
			cur = bundles
			parse = true
			break
		default:
			buffer.WriteString(trim + "\n")
		}
		if parse {
			var err error
			switch pre {
			case versions:
				err = toml.Unmarshal(buffer.Bytes(), &data.Versions)
			case libraries:
				err = toml.Unmarshal(buffer.Bytes(), &data.Libraries)
			case plugins:
				err = toml.Unmarshal(buffer.Bytes(), &data.Plugins)
			case bundles:
				err = toml.Unmarshal(buffer.Bytes(), &data.Bundles)
			}
			if err != nil {
				panic(err)
			}
			buffer.Reset()
			parse = false
		}
	}

	for key, v := range data.Versions {
		fmt.Println("ver", key, v)
	}
	for key, v := range data.Libraries {
		fmt.Println("lib", key, v)
	}
	for key, v := range data.Plugins {
		fmt.Println("plugin", key, v)
	}

	return data
}

func (r LibVersion) UpdateWithClient(c *http.Client) {
	buf := new(bytes.Buffer)
	for _, v := range r.Libraries {
		log.Println("dep current:", v)
		dep, err := handleUpdateDep(v.Dep(), c)
		if err != nil {
			log.Printf("update dep err %s\n", err)
			continue
		}
		log.Println("dep current end:", dep.ToRaw(dep.Version))
		buf.WriteString(dep.ToRaw(dep.Version) + "\n")
	}
	os.WriteFile("new.txt", buf.Bytes(), 0644)
}
